<template>
  <div class="app-container">
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
    <el-table
      :data="tableData"
      border
      highlight-current-row
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column
        v-for="item of tableHeader"
        :key="item"
        :prop="item"
        :label="item"
      />
    </el-table>
  </div>
</template>

<script>

// 引入工具方法后端接口需要改数据
import { getImportData } from '@/utils/excelData'

// 引入接口导入数据
import { importEmployee } from '@/api/employees'

export default {
  name: 'UploadExcel',
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header

      // 导入的数据格式转换
      const data = getImportData(results)

      // 掉接口导入数据
      await importEmployee(data)

      // 路由跳转到之前的页面
      this.$router.back()
    }
  }
}
</script>
